import { defineStore } from 'pinia'
import router from '@/router'
import api from '@/api'
// import md5 from 'crypto-js/md5'
import { fomatRoute } from '@/router/getRoutes.js'

export const useUserStore = defineStore('user', {
  state () {
    const routers = JSON.parse(localStorage.getItem('routers') || '[]')
    return {
      token: localStorage.getItem('token'),
      userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      departs: JSON.parse(localStorage.getItem('departs') || '[]'),
      userRoles: [],
      routers,
      formatRouter: fomatRoute(routers),
      dicts: JSON.parse(localStorage.getItem('dicts') || '{}')
    }
  },
  getters: {},
  actions: {
    // 设置字典
    setDicts (dicts = {}) {
      this.dicts = {
        ...dicts,
        // 本地默认字典
        ...window.config.defaultDicts
      }
      localStorage.setItem('dicts', JSON.stringify(this.dicts))
    },
    // 设置令牌
    setToken (token = '') {
      this.token = token
      localStorage.setItem('token', token)
    },
    // 设置用户信息
    setUserInfo (userInfo = {}) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    // 设置角色
    setUserRoles (userRoles = []) {
      this.userRoles = userRoles
    },
    // 设置部门
    setDeparts (departs = []) {
      this.departs = departs
      localStorage.setItem('departs', JSON.stringify(departs))
    },
    // 设置路由
    setRouters (routers = []) {
      this.routers = routers
      this.formatRouter = fomatRoute(routers)
      localStorage.setItem('routers', JSON.stringify(routers))
    },
    // 获取路由
    async getRouters () {
      const routeData = await api.getRoutes()
      this.setRouters(routeData.data.menu)
      let list = fomatRoute(routeData.data.menu)
      return Promise.resolve(list)
    },
    // 登录
    async login (param) {
      const { data } = await api.login({ ...param })
      console.log(data)
      const { token } = data
      this.setToken(token)
      const {
        data: { userInfo, userRoles, constants, departs }
      } = await api.getInfo(token)
      this.setUserInfo(userInfo)
      this.setUserRoles(userRoles)
      this.setDicts(constants)
      this.setDeparts(departs)
      await this.getRouters()
      this.addRoutes()
      return Promise.resolve(data)
    },
    // 添加路由
    addRoutes () {
      this.formatRouter.forEach((item) => {
        router.addRoute('layout', item)
      })
    },
    // 注销
    logout () {
      this.setToken()
      this.setUserInfo()
      this.setUserRoles()
      this.setDeparts()
      this.setDicts()
      this.setRouters()
      window.location.reload()
    }
  }
})
